package com.gmail.at.dengtooling.util;

import java.io.IOException;
import java.math.BigInteger;

/**
 * 
 * @author Deng Tooling
 * @version 1.0
 */
public class Type {

	/**
	 * convert a bytes array to int
	 * 
	 * @param b
	 *            bytes array
	 * @return an int value of b
	 */
	public static int bytes2int(byte[] b) {
		int mask = 0xff;
		int temp = 0;
		int res = 0;
		for (int i = 0; i < 4; i++) {
			res <<= 8;
			temp = b[i] & mask;
			res |= temp;
		}
		return res;
	}

	/**
	 * convert a bytes array to int
	 * 
	 * @param b
	 *            bytes array
	 * @param pos
	 *            start position
	 * @return int value of b
	 */
	public static int bytes2int(byte[] b, int pos) {
		int mask = 0xff;
		int temp = 0;
		int res = 0;
		for (int i = pos; i < 4 + pos; i++) {
			res <<= 8;
			temp = b[i] & mask;
			res |= temp;
		}
		return res;
	}

	public static byte[] int2bytes(int num) {
		byte[] b = new byte[4];
		for (int i = 0; i < 4; i++) {
			b[i] = (byte) (num >>> (24 - i * 8));
		}
		return b;
	}
	
	/**
	 *  convert a bytes array to String
	 * @param b
	 * @return
	 * @throws IOException
	 */
	public String byte2string(byte[] b) throws IOException
	{
		int len = bytes2int(b);
		byte[] res = new byte[len];
		System.arraycopy(b, 4, res, 0, len);
		String str=new String(res,"ISO-8859-1");
		return str;
	}
	
	public String byte2string(byte[] b,int pos) throws IOException
	{
		int len = bytes2int(b,pos);
		byte[] res = new byte[len];
		System.arraycopy(b, pos + 4, res, 0, len);
		String str=new String(res,"ISO-8859-1");
		return str;
	}
	
	/**
	 *  convert String to bytes array
	 * @param s
	 * @return
	 */
	public byte[] string2byte(String s){
		byte[] res = s.getBytes();
		int len = res.length;
		byte[] lens=int2bytes(len);
		byte[] b=new byte[len+4];
		
		System.arraycopy(lens, 0, b, 0, 4);
		System.arraycopy(res, 4, b, 0, len);
		return b;
	}
	/**
	 *  convert a bytes array to BigInteger
	 * @param b
	 * @return
	 * @throws IOException
	 */
	public BigInteger byte2mpint(byte[] b) throws IOException
	{
		int len = bytes2int(b);
		byte[] res = new byte[len];
		System.arraycopy(b, 4, res, 0, len);
		BigInteger bigInt=new BigInteger(res);
		return bigInt;
	}
	
	public BigInteger byte2mpint(byte[] b,int pos) throws IOException
	{
		int len = bytes2int(b,pos);
		byte[] res = new byte[len];
		System.arraycopy(b, pos + 4, res, 0, len);
		BigInteger bigInt=new BigInteger(res);
		return bigInt;
	}
	
	/**
	 *  convert BigInteger to bytes array
	 * @param s
	 * @return
	 */
	public byte[] mpint2byte(BigInteger bint){
		byte[] res = bint.toByteArray();
		int len = res.length;
		byte[] lens=int2bytes(len);
		byte[] b=new byte[len+4];
		
		System.arraycopy(lens, 0, b, 0, 4);
		System.arraycopy(res, 4, b, 0, len);
		return b;
	}
}